//
//  DetailViewController.m
//  BabyBedtimeStory
//
//  Created by qianfeng on 15-6-21.
//  Copyright (c) 2015年 张鹏毅. All rights reserved.
//

#import "DetailViewController.h"
#import "StoryModel.h"
#import "AFNetworking.h"
#import "DetailCell.h"
#import "JHRefresh.h"
#import "UIImageView+WebCache.h"
#import "PlayingViewController.h"
#import "localViewController.h"
#import "NSString+Hashing.h"

#define kScreenSize [UIScreen mainScreen].bounds.size

@interface DetailViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    AFHTTPRequestOperationManager *_manager;
}
@property (nonatomic,strong) localViewController *loac;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataArr;
@property (nonatomic,strong) NSMutableArray *arrData;
@property (nonatomic,strong) StoryModel *model;
@end

@implementation DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = self.title;
    self.isRefreshing = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.loac = [[localViewController alloc]init];
    [self Init];
    [self creatTableView];
    [self creatAf];
    [self StartDownloadingData];
    [self beginRefreshing];
}

-(void)Init{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(0, 0, 30, 30);
    [button setImage:[[UIImage imageNamed:@"ic_nac_bar_back_left"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = item;
}

#pragma mark - 创建tableView
-(void)creatTableView{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kScreenSize.width, kScreenSize.height-64-49)];
    self.dataArr = [[NSMutableArray alloc]init];
    self.arrData = [[NSMutableArray alloc]init];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"DetailCell" bundle:nil] forCellReuseIdentifier:@"DetailCell"];
    [self.view addSubview:self.tableView];
}

-(void)creatAf{
    _manager = [AFHTTPRequestOperationManager manager];
    _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
}

#pragma mark - 下载数据
-(void)StartDownloadingData{
    __weak typeof(self) weakSelf = self;
    
    NSString *url = [NSString stringWithFormat:kUrl,self.id];
    [_manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dictAata = dict[@"data"];
            NSDictionary *dictAlbum = dictAata[@"album"];
            StoryModel *model = [[StoryModel alloc]init];
            [model setValuesForKeysWithDictionary:dictAlbum];
            [weakSelf.arrData addObject:model];
            
            NSDictionary *dictContent = dictAata[@"content_list"];
            NSArray *arr = dictContent[@"data_list"];
            for (NSDictionary *dictcontent_list in arr) {
                StoryModel *model = [[StoryModel alloc]init];
                [model setValuesForKeysWithDictionary:dictcontent_list];
                [weakSelf.dataArr addObject:model];
            }
            [weakSelf.tableView reloadData];
            [self creatHeader];
            [weakSelf stopRefreshing];
//            [weakSelf tableViewDidSelect];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [weakSelf stopRefreshing];
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DetailCell" forIndexPath:indexPath];
    StoryModel *modelImage = self.arrData.lastObject;
    [cell showWithModelImage:modelImage];
    StoryModel *model = self.dataArr[indexPath.row];
    [cell showWithModel:model];
    return cell;
}

#pragma mark - cell选中的时候
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *myCahaePath =[NSHomeDirectory() stringByAppendingString:@"/Documents/"];
    NSDirectoryEnumerator *enumator = [[NSFileManager defaultManager]enumeratorAtPath:myCahaePath];
    BOOL isYes = NO;
    for (NSString *fileName in enumator) {
        NSLog(@"%@",fileName);
        if ([fileName isEqualToString:[NSString stringWithFormat:@"%@.mp3",[[self.dataArr[indexPath.row]audio_64_url] MD5Hash]]]) {
            isYes = YES;
            break;
        }else{
            isYes = NO;
        }
    }
    if (isYes) {
        [self creatAlter:@"本地已下载,是否转到本地" number:indexPath.row];
    }else{
        [self networkPlayingNumber:indexPath.row];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90;
}

#pragma mark - 头视图
-(void)creatHeader{
    StoryModel *model = self.arrData.lastObject;
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenSize.width, 220)];
    [imageView sd_setImageWithURL:[NSURL URLWithString:model.image_url] placeholderImage:[UIImage imageNamed:@"yujiazai"]];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 220, kScreenSize.width, 50)];
    label.numberOfLines = 0;
    label.font = [UIFont fontWithName:@"Didot" size:13];
    label.text = model.describe;
    
    UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 270, kScreenSize.width, 20)];
    image.userInteractionEnabled = YES;
    image.backgroundColor = [UIColor lightGrayColor];
    image.alpha = 0.2;
    
    label.font = [UIFont fontWithName:@"Didot" size:13];
    UIImageView *HImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 64, kScreenSize.width, 290)];
    HImageView.userInteractionEnabled = YES;
    
    
    [HImageView addSubview:imageView];
    [HImageView addSubview:image];
    [HImageView addSubview:label];
    self.tableView.tableHeaderView = HImageView;
}

#pragma mark - 刷新
-(void)beginRefreshing{
    __weak typeof(self) weakSelf = self;
    if (self.isRefreshing) {
        return;
    }
    [self.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        weakSelf.isRefreshing = YES;
        [weakSelf StartDownloadingData];
    }];
}

-(void)stopRefreshing{
    if (self.isRefreshing) {
        self.isRefreshing = NO;
        [self.tableView headerEndRefreshingWithResult:JHRefreshResultSuccess];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)btnClick{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - 返回选中指定行
//-(void)tableViewDidSelect{
//    if (self.isBool == 1) {
//        NSIndexPath *ip=[NSIndexPath indexPathForRow:self.SelectNum inSection:0];
//        [self.tableView selectRowAtIndexPath:ip animated:NO scrollPosition:UITableViewScrollPositionBottom];
//        self.isBool = -1;
//    }
//}

-(void)creatAlter:(NSString *)str number:(NSInteger)number{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:str preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        [self networkPlayingNumber:number];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        localViewController *vc = [[localViewController alloc]init];
        vc.str = [NSString stringWithFormat:@"%@.mp3",[[self.dataArr[number] audio_64_url] MD5Hash]];
        [[NSNotificationCenter defaultCenter]postNotificationName:kFabcdefge object:nil];
        [self.navigationController pushViewController:vc animated:YES];
    }]];
    [[[[UIApplication sharedApplication]keyWindow]rootViewController] presentViewController:alert animated:YES completion:nil];
}

-(void)networkPlayingNumber:(NSInteger)number{
    PlayingViewController *vc = [[PlayingViewController alloc]init];
    vc.SelectNum = number;
    vc.count = self.dataArr.count;
    vc.dataArr = self.dataArr;
    vc.model = self.dataArr[number];
    [[NSNotificationCenter defaultCenter]postNotificationName:kFabcdefg object:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

@end
